//
//  MTStartupUtilities.m
//  Tazama NGO
//
//  Created by Jack Sheriff on 10/26/11.
//  Copyright (c) 2011 The MITRE Corporation. All rights reserved.
//

#import "MTStartupUtilities.h"

@implementation MTStartupUtilities

+ (void)copyFileFromBundleToDocumentsDirectory:(NSString *)fileName {
	//Get the path to the file in the documents directory
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *fileDocumentsPath = [documentsDirectory stringByAppendingPathComponent:fileName];
    
    // Does the file exist already?
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileDocumentsPath];
	if(!fileExists)
	{
        // The file does not exist in the documents directory.  Copy it from the bundle.
		NSString *fileBundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
        NSError *error;
		BOOL didCopyFile = [[NSFileManager defaultManager] copyItemAtPath:fileBundlePath toPath:fileDocumentsPath error:&error];
        
        // Check for a failure to copy
		if (!didCopyFile) {
			NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]);
        }
	}
}

+ (void)registerDefaultsFromSettingsBundle {
    // Get the path to the settings bundle
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }
    
    // Fill the preferences array with the settings from the settings bundle
    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
    
    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for (NSDictionary *preferemceSpecification in preferences) {
        NSString *key = [preferemceSpecification objectForKey:@"Key"];
        if (key) {
            [defaultsToRegister setObject:[preferemceSpecification objectForKey:@"DefaultValue"] forKey:key];
        }
    }
    
    // Add the settings to the standard user defaults
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
    [defaultsToRegister release];
}

@end
